package com.yc.user.controller;


import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.api.CommonPage;
import com.yc.api.CommonResult;
import com.yc.base.BaseController;
import com.yc.constant.Constant;
import com.yc.dict.annotation.ResponseDict;
import com.yc.enums.StatusEnum;
import com.yc.helper.LoginHelper;
import com.yc.user.entity.User;
import com.yc.user.service.IUserService;
import com.yc.user.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author bao
 * @since 2021-12-08
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@ResponseDict
@RequestMapping("/v1/user")
@Api(value = "UserController", tags = "后台用户表")
public class UserController extends BaseController {

    private final IUserService userService;

    @PostMapping("/add")
    @ApiOperation(value = "创建User", notes = "创建User")
    @SaCheckPermission(value = {"management:user:add"})
    public CommonResult<?> create(@RequestBody JSONObject params) {
        User user = JSONUtil.toBean(params, User.class);
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPhone()) ||
                StrUtil.isBlank(user.getNickname()) || StrUtil.isBlank(user.getEmail())) {
            return CommonResult.validateFailed();
        }
        user.setPassword(Constant.password);
        List<Long> roleIds = params.getBeanList("roleIds", Long.class);
        UserVo userVo = userService.create(user, roleIds);
        if (ObjectUtil.isNotNull(userVo)) {
            return CommonResult.success(userVo);
        }
        return CommonResult.failed();
    }

    @PostMapping("/deleteByIds")
    @ApiOperation(value = "删除User", notes = "删除User")
    @SaCheckPermission(value = {"management:user:delete"})
    public CommonResult<?> deleteByIds(@RequestBody List<Long> ids) {
        boolean isOk = userService.delete(ids);
        if (isOk) {
            return CommonResult.success();
        }
        return CommonResult.failed();
    }

    @PostMapping("/updateById/{id}")
    @ApiOperation(value = "更新User", notes = "更新User")
    @SaCheckPermission(value = {"management:user:update"})
    public CommonResult<?> updateById(@PathVariable("id") Long id, @RequestBody JSONObject params) {
        User user = JSONUtil.toBean(params, User.class);
        user.setId(id);
        if (ObjectUtil.isNull(id) || StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPhone()) ||
                StrUtil.isBlank(user.getNickname()) || StrUtil.isBlank(user.getEmail())) {
            return CommonResult.validateFailed();
        }
        List<Long> roleIds = params.getBeanList("roleIds", Long.class);
        UserVo userVo = userService.update(user, roleIds);
        if (ObjectUtil.isNotNull(userVo)) {
            return CommonResult.success(userVo);
        }
        return CommonResult.failed();
    }

    @PostMapping("/queryById/{id}")
    @ApiOperation(value = "根据Id获取User", notes = "根据Id获取User")
    public CommonResult<?> queryById(@PathVariable("id") Long id) {
        UserVo user = userService.queryById(id);
        if (user != null) {
            return CommonResult.success(user);
        }
        return CommonResult.failed();
    }

    @PostMapping("/list")
    @ApiOperation(value = "获取User列表", notes = "获取User列表")
    public CommonResult<Object> listAll() {
        List<User> list = userService.selectList();
        return CommonResult.success(list);
    }

    @PostMapping("/page")
    @ApiOperation(value = "获取User列表", notes = "获取User列表")
    public CommonResult<Object> pageAll(@RequestBody JSONObject params) {
        int pageNum = params.getInt("pageNum", 1);
        int pageSize = params.getInt("pageSize", 25);
        String username = params.getStr("username", null);
        StatusEnum statusEnum = params.getEnum(StatusEnum.class, "status");
        List<Long> roleIdList = params.getBeanList("roleIds", Long.class);
        Long postId = params.getLong("postId");
        IPage<UserVo> page = userService.selectPage(new Page<>(pageNum, pageSize), username, roleIdList, postId, statusEnum);
        return CommonResult.success(CommonPage.restPage(page));
    }

    @PostMapping("/password")
    @ApiOperation(value = "修改密码", notes = "修改密码")
    public CommonResult<?> updateUserPassword() {
        JSONObject params = getParams();
        String oldPassword = params.getStr("oldPassword", null);
        String newPassword = params.getStr("newPassword", null);
        if (StrUtil.isBlank(oldPassword) || StrUtil.isBlank(newPassword)) {
            return CommonResult.validateFailed();
        }
        int status = userService.updatePassword(LoginHelper.getUserId(), oldPassword, newPassword);
        if (status > 0) {
            return CommonResult.success();
        } else if (status == -1) {
            return CommonResult.failed("用户不存在");
        } else if (status == -2) {
            return CommonResult.failed("原密码不一致");
        } else {
            return CommonResult.failed();
        }
    }

    @PostMapping("/queryUserInfo")
    @ApiOperation(value = "查询用户中心", notes = "查询用户中心")
    public CommonResult<?> queryUserInfoById() {
        long id = LoginHelper.getUserId();
        return CommonResult.success(userService.queryById(id));
    }

    @PostMapping("/updateUserInfo")
    @ApiOperation(value = "修改用户中心", notes = "修改用户中心")
    public CommonResult<?> updateUserInfoById(@RequestBody User user) {
        long id = LoginHelper.getUserId();
        user.setId(id);
        boolean isOk = userService.updateById(user);
        if (isOk) {
            return CommonResult.success(user);
        }
        return CommonResult.failed();
    }
}
